# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
from urllib.parse import urlencode, quote
import requests, re, json
from threading import Thread
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "健康保（多倍版)重大疾病保险保险计划"

    # 生产产品信息
    def genProductInfo(self):
        plan = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(0, 18)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["400000", "450000", "500000"],
                # 保障期限
                "expire": ["70岁"],
                # 交费间隔
                "interval": ["10", "15", "20"],
                # 交费方式
                "payType": ["年交"],
                # 意外身故保险金 1 投保 0 不投保
                "accidentDeath": ["1"],
                # 恶性肿瘤住院津贴
                "cancerHospital": ["0", "1"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(0, 18)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["300000", "350000", "400000", "450000", "500000"],
                # 保障期限
                "expire": ["80岁", "终身"],
                # 交费间隔
                "interval": ["10", "15", "20", "30"],
                # 交费方式
                "payType": ["年交"],
                # 意外身故保险金 1 投保 0 不投保
                "accidentDeath": ["0", "1"],
                # 恶性肿瘤住院津贴
                "cancerHospital": ["0", "1"]
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(18, 36)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["400000", "450000", "500000", "550000", "600000"],
                # 保障期限
                "expire": ["70岁"],
                # 交费间隔
                "interval": ["10", "15", "20"],
                # 交费方式
                "payType": ["年交"],
                # 意外身故保险金 1 投保 0 不投保
                "accidentDeath": ["1"],
                # 恶性肿瘤住院津贴
                "cancerHospital": ["0", "1"]
            },
            "planD": {
                # 年龄段
                "year": [str(i) for i in range(18, 36)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["300000", "350000", "400000", "450000", "500000", "550000", "600000"],
                # 保障期限
                "expire": ["80岁", "终身"],
                # 交费间隔
                "interval": ["10", "15", "20", "30"],
                # 交费方式
                "payType": ["年交"],
                # 意外身故保险金 1 投保 0 不投保
                "accidentDeath": ["0", "1"],
                # 恶性肿瘤住院津贴
                "cancerHospital": ["0", "1"]
            },
            "planE": {
                # 年龄段
                "year": [str(i) for i in range(36, 41)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["400000", "450000", "500000", "550000", "600000"],
                # 保障期限
                "expire": ["70岁"],
                # 交费间隔
                "interval": ["10", "15"],
                # 交费方式
                "payType": ["年交"],
                # 意外身故保险金 1 投保 0 不投保
                "accidentDeath": ["1"],
                # 恶性肿瘤住院津贴
                "cancerHospital": ["0", "1"]

            },
            "planF": {
                # 年龄段
                "year": [str(i) for i in range(36, 41)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["300000", "350000", "400000", "450000", "500000", "550000", "600000"],
                # 保障期限
                "expire": ["80岁"],
                # 交费间隔
                "interval": ["10", "15", "20"],
                # 交费方式
                "payType": ["年交"],
                # 意外身故保险金 1 投保 0 不投保
                "accidentDeath": ["0", "1"],
                # 恶性肿瘤住院津贴
                "cancerHospital": ["0", "1"]

            },
            "planG": {
                # 年龄段
                "year": [str(i) for i in range(36, 41)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["300000", "350000", "400000", "450000", "500000", "550000", "600000"],
                # 保障期限
                "expire": ["终身"],
                # 交费间隔
                "interval": ["10", "15", "20", "30"],
                # 交费方式
                "payType": ["年交"],
                # 意外身故保险金 1 投保 0 不投保
                "accidentDeath": ["0", "1"],
                # 恶性肿瘤住院津贴
                "cancerHospital": ["0", "1"]

            },
            "planH": {
                # 年龄段
                "year": [str(i) for i in range(41, 46)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["400000", "450000", "500000"],
                # 保障期限
                "expire": ["70岁"],
                # 交费间隔
                "interval": ["10"],
                # 交费方式
                "payType": ["年交"],
                # 意外身故保险金 1 投保 0 不投保
                "accidentDeath": ["1"],
                # 恶性肿瘤住院津贴
                "cancerHospital": ["0", "1"]

            },
            "planI": {
                # 年龄段
                "year": [str(i) for i in range(41, 46)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["300000", "350000", "400000", "450000", "500000"],
                # 保障期限
                "expire": ["80岁"],
                # 交费间隔
                "interval": ["10", "15"],
                # 交费方式
                "payType": ["年交"],
                # 意外身故保险金 1 投保 0 不投保
                "accidentDeath": ["0", "1"],
                # 恶性肿瘤住院津贴
                "cancerHospital": ["0", "1"]

            },
            "planJ": {
                # 年龄段
                "year": [str(i) for i in range(41, 46)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["300000", "350000", "400000", "450000", "500000"],
                # 保障期限
                "expire": ["终身"],
                # 交费间隔
                "interval": ["10", "15", "20"],
                # 交费方式
                "payType": ["年交"],
                # 意外身故保险金 1 投保 0 不投保
                "accidentDeath": ["0", "1"],
                # 恶性肿瘤住院津贴
                "cancerHospital": ["0", "1"]

            }

        }
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["money"], plan[k]["expire"],
                             plan[k]["interval"], plan[k]["payType"], plan[k]["accidentDeath"],
                             plan[k]["cancerHospital"]):
                if v[6] == "1":
                    accidentDeath = v[2]
                else:
                    accidentDeath = "0"
                if v[7] == "1":
                    cancerHospital = v[2]
                else:
                    cancerHospital = "0"

                data = Helper.formatProductInfo(plan[k], v)
                data["accidentDeath"] = accidentDeath
                data["cancerHospital"] = cancerHospital
                print(data)
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def requestJson(self, dt=None, mysql=None):
        init_items = [{"dutyCode": "167001", "dutyAmnt": dt["money"]}]
        ext_c = {
            "accidentDeath": dt["accidentDeath"],
            "cancerHospital": dt["cancerHospital"]
        }
        for key in ext_c:
            if key == "accidentDeath" and ext_c["accidentDeath"] != "0":
                init_items.append({"dutyCode": "167002", "dutyAmnt": ext_c["accidentDeath"]})
            elif key == "cancerHospital" and ext_c["cancerHospital"] != "0":
                init_items.append({"dutyCode": "167003", "dutyAmnt": ext_c["cancerHospital"]})

        age = str(2020 - int(dt["year"]))
        sex = "0" if dt["gender"] == "M" else "1"
        ext_items = json.dumps(init_items)
        add_items = (ext_items.replace("[", "").replace("]", ""))
        data = {
            'insuredsStr': '[{"birthday": "' + age + '-01-01", "sex": "' + sex + '", "planInfos":[{"riskCode":"I165","mainRiskCode":"I165","planCode":"50","planPeriod":"' +
                           dt["expire"] + '","payType":"0","payEndYearFlag":"Y","payEndYear":' + dt[
                               "interval"] + ',"dutys": [' + add_items + ']}]}]',
            'isOrder': '0',
            'productID': '46',
        }
        payload = urlencode(data).replace("+", "")
        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)
        if r.status_code == 200 and "无法计算保费！" not in r.text:
            price = Helper.decimalParse(re.search(r'"premiun":(.*?),', r.text).group(1))
            data = {
                "name": self.name,
                "id": dt["id"],
                "price": price
            }
            print(data)
            mysql.updatePrice(data)
        else:
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            mysql.updateTask(data)
            print("\n/*产品价格信息更新失败：%d*/" % dt["id"])

    def main(self, mysql):
        while True:
            # 随机领取一条数据
            dt = mysql.randTask(self.name)
            if not dt:
                print("产品价格抓取完成~~~")
                return
                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            mysql.updateTask(data)
            self.requestJson(dt, mysql)

    def startProcess(self):
        threads = []
        for i in range(5):
            mysql = MysqlClient()
            t = Thread(target=self.main, args=(mysql,))
            t.start()
            threads.append(t)
        for t in threads:
            t.join()

